from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.db.models import Q
from .models import Product

def home(request):
    """首页视图"""
    featured_products = Product.objects.all()[:6]  # 获取最新的6个商品
    return render(request, 'home.html', {'products': featured_products})

def product_list(request):
    """商品列表视图"""
    query = request.GET.get('q', '')
    products = Product.objects.all()
    
    if query:
        products = products.filter(
            Q(name__icontains=query) |  # 搜索商品名称
            Q(description__icontains=query)  # 搜索商品描述
        )
    
    return render(request, 'products/product_list.html', {
        'products': products,
        'query': query
    })

def product_detail(request, pk):
    """商品详情视图"""
    product = get_object_or_404(Product, pk=pk)
    return render(request, 'products/product_detail.html', {'product': product})
